package com.enqualcomm.kids.activities;

import android.widget.Button;
import android.widget.TextView;

import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.bean.StringMessage;
import com.enqualcomm.kids.bean.VoiceSchedule;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.mvp.voiceschedule.Pcm2Amr;
import com.enqualcomm.kids.mvp.voiceschedule.SpeechSynthesizerModel;
import com.enqualcomm.kids.mvp.voiceschedule.VoiceScheduleModel;
import com.enqualcomm.kids.network.socket.response.QueryUserTerminalInfoResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.enqualcomm.kids.view.dialog.EditDialogCallBack;
import com.enqualcomm.kids.view.dialog.MyDateTimePickerDialog2;
import com.enqualcomm.kids.view.dialog.MyEditDialog3;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.io.File;

import common.utils.MyFrontUtil;
import common.utils.PromptUtil;
import de.greenrobot.event.EventBus;
import rx.Subscription;
import rx.functions.Action1;

@EActivity(R.layout.activity_voice_schedule_commit)
public class VoiceScheduleCommitActivity extends BaseActivity {

    @Extra("terminal")
    TerminallistResult.Terminal terminal;
    @Extra("voiceSchedule")
    VoiceSchedule voiceSchedule;

    @ViewById(R.id.date_time_tv)
    TextView date_time_tv;
    @ViewById(R.id.content_tv)
    TextView content_tv;
    @ViewById(R.id.title_bar_terminal_name_tv)
    TextView title_bar_terminal_name_tv;
    @ViewById(R.id.send_to_watch_btn)
    Button send_to_watch_btn;

    SpeechSynthesizerModel synthesizerModel;
    private Subscription subscription;
    private QueryUserTerminalInfoResult.Data info;

    @AfterViews
    void setupViews() {

        info = new UserTerminalDefault(terminal.userterminalid).getInfo();
        setupTitleIcon(info, terminal.terminalid, terminal.userterminalid, getString(R.string.remind_new_one));
        MyFrontUtil.initTextViewText(this, title_bar_terminal_name_tv, info.name,
                getString(R.string.r_new_begin), getString(R.string.r_new_end), 1, info.name.length() + 1);
//        findViewById(R.id.top_layout).setBackgroundResource(R.color.colorPrimary);
        MyFrontUtil.initTextViewText(this, send_to_watch_btn, info.name,
                getString(R.string.v_commit_begin), getString(R.string.v_commit_end), 3, info.name.length() + 3);

        date_time_tv.setText(voiceSchedule.datetime);
        content_tv.setText(voiceSchedule.content);

        synthesizerModel = new SpeechSynthesizerModel(this);
        synthesizerModel.onSynthesizerCompleted().subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if (s != null) {
//                    MyLogger.jLog().i(s);

                    String amrFileName = Pcm2Amr.convert(s);
                    if (amrFileName != null) {
                        voiceSchedule.filePath = amrFileName;
                        sendToServer();
                    } else {
                        hideProgress();
                        PromptUtil.toast(getApplicationContext(), getString(R.string.failed_to_send));
                    }

                    File file = new File(s);//删掉pcm文件
                    if (file.exists()) {
                        file.delete();
                    }
                } else {//语音合成失败
                    hideProgress();
                    PromptUtil.toast(getApplicationContext(), getString(R.string.failed_to_send));
                }
            }
        });
    }


    private void sendToServer() {
        subscription = VoiceScheduleModel.sendVoiceSchedule(voiceSchedule, terminal.terminalid, info.relation).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                hideProgress();
//                MyLogger.jLog().i(s);
                if (s == null) {
                    PromptUtil.toast(getApplicationContext(), getString(R.string.failed));
                } else {
                    if (VoiceScheduleModel.OUT_OF_LIMIT.equals(s)) {
                        PromptUtil.toast(getApplicationContext(), getString(R.string.too_much_to_delete));
                    }

                    EventBus.getDefault().post(new StringMessage(StringMessage.ADD_VOICE_SCHEDULE));//发送成功，列表界面需要刷新
                    finish();
                }

                File file = new File(voiceSchedule.filePath);//删除amr文件
                if (file.exists()) {
                    file.delete();
                }
            }
        });
    }

    @Click(R.id.title_bar_left_iv)
    void finishActivity() {
        finish();
    }

    @Click(R.id.send_to_watch_btn)
    void sendToWatch() {
        showProgress();
        voiceSchedule.datetime = date_time_tv.getText().toString();
        voiceSchedule.content = content_tv.getText().toString();
        synthesizerModel.start(voiceSchedule.content);
    }

    @Click(R.id.voice_schedule_datetime_rl)
    void showSetDatetimeDialog() {
        String s = date_time_tv.getText().toString().replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "");
        new MyDateTimePickerDialog2(this, null, s, 4, date_time_tv).show();
    }

    @Click(R.id.voice_schedule_content_rl)
    void showSetContentDialog() {
        String string = content_tv.getText().toString();
        new MyEditDialog3(this, getString(R.string.remind_content), new EditDialogCallBack() {
            @Override
            public void inputOver(String content, String phone) {
                content_tv.setText(content);
            }
        }, string).show();
    }

    @Override
    protected void onDestroy() {
        synthesizerModel.destroy();
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
        super.onDestroy();
    }
}
